/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    IconButton,
    IconX,
    useToast,
    InputPure,
    SuffixInput,
    Dialog,
    Text,
    Button,
    useTheme,
    InputLine,
    Input,
    IconCloud,
    List,
    ListItem,
    Avatar,
    ResponsivePopover,
    MenuList,
    MenuItem,
    IconPackage,
    IconRefButton,
    IconMoreVertical,
    Select,
    CommitInput,
    CheckSwitch, InputDatalist, Layer, IconChevronUp, IconChevronDown, Collapse, useCollapse
} from "customize-easy-ui-component";

import {Dispatch, SetStateAction, useContext} from "react";
import RoutingContext from "../../src/routing/RoutingContext";
import {ContainLine, TransparentInput} from "../../src/comp/base";
import {usePreloadedQuery, useQueryLoader} from "react-relay/hooks";
import {AddressChooseQueryResponse} from "../../src/common/geo/__generated__/AddressChooseQuery.graphql";
import {Link as RouterLink} from "../../src/routing/Link";
import {css} from "@emotion/react";
import {子设备品种, 设备品种, 设备种类, 设备类别} from "../../src/dict/eqpComm";
import {CityChoose} from "../../src/common/geo/CityChoose";
import {CountyChoose} from "../../src/common/geo/CountyChoose";
import {TownChoose} from "../../src/common/geo/TownChoose";
import useCreateDeviceMutation from "../../src/device/useCreateDeviceMutation";
import useAddUnitMutation from "../../src/unit/useAddUnitMutation";
import useNewPositionMutation from "../../src/common/geo/useNewPositionMutation";
import {PositionList, PositionListInner} from "../../src/common/geo/PositionList";
import {ProvinceChoose} from "../../src/common/geo/ProvinceChoose";
import {DivisionChoose} from "../../src/unit/division/DivisionChoose";
import {VillageChoose} from "../../src/common/geo/VillageChoose";
import {ErrorBoundary} from "react-error-boundary";
///import { DivisionChooseQuery } from "./__generated__/DivisionChooseQuery.graphql";
const graphql = require("babel-plugin-relay/macro");
const AddressChooseQuery = require('../../src/common/geo/__generated__/AddressChooseQuery.graphql');
//const PositionListQuery = require('./__generated__/PositionListQuery.graphql');


export const 公众聚集场所=['学校','幼儿园','医院','车站','客运码头','商场','体育场馆','展览馆','公园','其它公众聚集场所'];


interface AddressChooseProps {
    //当前id所指向的挂接对象模型的给用户看的关键名:标题= 单位名字;
    name?: string | undefined;
    //清空编辑框已经选择的内容
    onCancel?: () => void;
    //行政区划默认查询的启动点，默认【中国】。
    //Address对象直接整个传递进来：
    pos?: any;
    //直接设置返回的状态变量。
    setEditorVar: Dispatch<SetStateAction<any>>;
}
//页面和数据分离后又要被迫整合在一块了？
//非高层次通用的组件。语义整合：　数据获取和规格化显示部分组合在一个文件内。前端graphql底层缓存：不见得每次都会发送请求给后端的。
//graphQL想把多个Query同时都坐在一个Hook函数里面一次性向后端读取，有许多障碍：页面分割，公用组件嵌套，父辈组件知晓子孙辈组件数据请求和参数还得传递数据，不过前端有缓存。

/**默认是不要显示国家级选择，都是【中国】,数据照样准备的，就是显示做屏蔽处理，显示点击能揭示状态。
 *【固定配置】 Country:1 中国；需要数据库配合一样数据！。
【删除】 不用了！
 */
export const AddressChoose= ({ name, pos, onCancel, setEditorVar, ...other }:AddressChooseProps) =>
{
    const theme = useTheme();
    const [open, setOpen] = React.useState(false);
    const [queryReference, loadQuery] = useQueryLoader(AddressChooseQuery);
    const handleSelect = React.useCallback((pos: any) => {
        setEditorVar(pos);
        setOpen(false);
    }, []);

  return (
   <React.Fragment>
    <SuffixInput  readOnly
          component={InputPure}
           value={name || '' }
           onClick={async () => {
                loadQuery({
                   id: ""
                });
              setOpen(true);
              //await onDialog!();   //编辑器来源，context已确定的；离开之前 需要临时保留数据。
            } }
          {...other}
    >
       <IconButton
          variant="ghost"
          icon={<IconX />}
          label="删除"
          css={{
            display: name ?  undefined : 'none'
          }}
          onClick={async (e) => {
            await onCancel!();
            e.preventDefault();
            e.stopPropagation();
          } }
        />
    </SuffixInput>

    <Dialog
        mobileFullscreen
        isOpen={open}
        onRequestClose={() => setOpen(false)}
        title="地址相关编辑"
    >
        <div >
            <React.Suspense fallback="等下马上来...">
                { queryReference && <AddressChooseInner queryReference={queryReference} onSelect={handleSelect} pos={pos}/> }
            </React.Suspense>
        </div>
    </Dialog>

   </React.Fragment>
  );
}


interface AddressChooseInnerProps {
    queryReference: any;
    onSelect: (pos: any) => void;
    pos?: any;
}
//外国的单位地址？如何处理？外国地址无法直接管理：{pos=null(或特殊构建的id),exadr=[外国粗略地址]} Country country;
//直接双层对话框 模态状态形式。
/**新申请地址：楼盘若想选择的话，必须选定街道乡镇级别行政区划才可以的。楼盘只能挑选，新添加楼盘数据维护后台独立做。
 * */
function AddressChooseInner({ queryReference, onSelect, pos }:AddressChooseInnerProps)
{
    //从对象关联进行延申：获取列表。首先需要一个初始出发点Node()?国家级别【1】=China;真正0号查询:findAllCountry():[Country];
    const data =usePreloadedQuery<typeof AddressChooseQuery>(
        graphql`
            query AddressChooseQuery($id: String) {
                getAllCountries(continent: $id) {
                    id,name,continent,collapse
                    __typename
                }
            }
      `,
        queryReference,
    );
    //有必要？做个 ES搜索引擎 索引，就是给no报告号的搜索加速？？
    const { getAllCountries: list }=data as AddressChooseQueryResponse;
    //const { countries:list }=object as any;
    //const isps = list && list.edges ? list.edges.map(edge => edge?.node) : [];
    const rep =list && list[0] && list[0].name;
    //  const { getReport: items }= (false)?  data! : {getReport:null};
    const theme = useTheme();
    //显示国家级? 'Q291bnRyeTox'代表中国; Country:1 Base64编码；与数据库数据必须一致！
    const [viewcntry, setViewcntry] = React.useState<boolean>(pos?.ad?.country?.id!=='Q291bnRyeTox' );

    const [country, setCountry] = React.useState<any>(pos?.ad?.country.id);
    const [province, setProvince] = React.useState<any>(pos?.ad?.province?.id);
    const [city, setCity] = React.useState<any>(pos?.ad?.city?.id);
    const [county, setCounty] = React.useState<any>(pos?.ad?.county?.id);
    const [town, setTown] = React.useState<any>(pos?.ad?.town?.id);
    const [adId, setAdId] = React.useState<string|null>(pos?.ad?.id);

    const [adrname, setAdrname] = React.useState(pos?.name);
    const [vlg, setVlg] = React.useState<any>(pos?.vlg);
    const [geo, setGeo] = React.useState<any>({lat:pos?.lat, lon:pos?.lon});
    const [seimp, setSeimp] = React.useState<any>(null);
    const [dense, setDense] = React.useState<any>(null);
    const [plcls, setPlcls] = React.useState<any>(null);

  //  const [inp, setInp] = React.useState(null);
    //外部dat不能加到依赖，变成死循环! const  dat =items&&items.data&&JSON.parse(items.data);  这dat每次render都变了？
    //从后端返回的数据可能items已经被修改了
/*    React.useEffect(() => {
        const  dat =rep&&rep.data&&JSON.parse(rep.data);
        dat && setInp(dat);
    }, [rep]);*/

  //  const {call:createfunc,doing, result:obj}= useNewPositionMutation();
    const [open, setOpen] = React.useState(false);
    const [position, setPosition] = React.useState<any>(null);
   /* const [posQreference, loadQuery] = useQueryLoader(PositionListQuery);*/
    const handleSelect = React.useCallback((pos: any) => {
        //console.log("签订pos去：捕获 ==id=[",  id,  "] name=", name );
       // setPosition(id);
       // setAdrname(name);
        setOpen(false);
        onSelect!(pos);    //仅传递一部分?
    }, []);

    const eos =useCollapse(true,true);
    //console.log("AddressChooseInner树状：sf捕获 position=[",  position,  "] vlg=", vlg );

    return (
     <React.Fragment>
        <div css={{
            margin: 'auto',
            background: "white",
            padding: theme.spaces.lg
        }}
        >
            {rep?
                <React.Fragment>
                    { viewcntry &&
                        <InputLine label={`国家和地区:`}>
                            <Select inputSize="md" css={{minWidth:'140px',fontSize:'1rem',padding:'0 1rem'}} divStyle={css`max-width:240px;`}
                                    value={country || ''}
                                    onChange={e => {
                                        setCountry!(e.currentTarget.value||undefined);
                                        setProvince(undefined);
                                        setCity(undefined);
                                        setCounty(undefined);
                                        setTown(undefined);
                                        setAdId(null);
                                        setVlg(undefined);
                                    }
                                    }
                            >
                                { list?.map((hit:any,i:number) => (
                                    <option key={i} value={hit?.id}>{{...hit}.name||''}</option>
                                ))}
                                <option value={''}>全部</option>
                            </Select>
                        </InputLine>
                    }

                <ProvinceChoose id={province} parentId={country} onSelect={(id)=>{
                    setProvince(id);
                    setCity(undefined);
                    setCounty(undefined);
                    setTown(undefined);
                    setAdId(null);
                    setVlg(undefined);
                } } />
                <CityChoose id={city} parentId={province} onSelect={(id)=>{
                    setCity(id);
                    setCounty(undefined);
                    setTown(undefined);
                    setAdId(null);
                    setVlg(undefined);
                } } />
                <CountyChoose id={county} parentId={city} setEditorVar={setCounty}
                          onSelect={(id)=>{
                              setAdId(null);
                              setTown(undefined);
                              setVlg(undefined);
                          } }
                />
                <TownChoose id={town} parentId={county}
                        onSelect={(id)=>{
                            setAdId(null);
                            setTown(id);
                            setVlg(undefined);
                        } }
                />

                </React.Fragment>
                :
                <Text variant="h5" css={{ textAlign: 'center' }}>
                    没找到此号码
                </Text>
            }

            <InputLine label={`地址(不需要行政区对应前缀):`}>
                <Input type="search" autoFocus  value={ adrname || ''}
                       onChange={e => setAdrname( e.currentTarget.value||undefined ) } />
            </InputLine>
{/*            <Button
                intent="primary"
                css={{ marginLeft: theme.spaces.sm }}
                onPress={() => {
                    //相当于菜单或 Link页面 切换时刻路由器触发的；需要准备好relay数据。
                    loadQuery({
                        where:{
                            name: adrname,  adId,
                            town,county,city,province,country,
                            },
                        first: 3,
                    });
                    setOpen(true);
                }}
            >搜索看(已登记)
            </Button>*/}
            <Button variant="ghost" intent="primary" css={{ marginLeft: theme.spaces.sm }}
                onPress={()=>setViewcntry(!viewcntry)}
            >{viewcntry?'不显示国家':'显示国家级'}</Button>
        </div>

         <Layer elevation={"sm"}     css={{ padding: '0.25rem' }}>
             <Button
                 variant="ghost"
                 intent="primary"
                 iconAfter={eos.show  ? <IconChevronUp /> : <IconChevronDown />}
                 {...eos.buttonProps}
                 css={{whiteSpace:'unset'}}
             >
                 {<Text variant="h5" css={{color: eos.show ? theme.colors.palette.red.base:undefined}}>扩展属性部分</Text>}
             </Button>
             <Collapse {...eos.collapseProps}  noAnimated>
                 { town &&
                     <InputLine label={'(选择)楼盘:'}>
                         <VillageChoose id={vlg?.id} name={vlg?.name}   setEditorVar={setVlg}
                                  onCancel={() => { setVlg(undefined) }}   parentId={adId || town} />
                     </InputLine>
                 }
                 <InputLine label={`是否在重要场所:`}>
                     <CheckSwitch  checked={seimp || false} onChange={e => setSeimp(seimp? undefined:true) } />
                 </InputLine>
                 <InputLine label={`是否人口密集区:`}>
                     <CheckSwitch  checked={dense || false} onChange={e => setDense(dense? undefined:true) } />
                 </InputLine>
                 <InputLine label={`设备使用场所(公众聚集场所标签):`}>
                     <InputDatalist
                         value={ plcls || ''}
                         onListChange={v => setPlcls(v ||undefined)}
                         datalist={公众聚集场所}
                     />
                 </InputLine>
                 <InputLine label={`纬度(点选地图坐标):`}>
                     <CommitInput  value={ geo.lat || ''}  onSave={txt => setGeo({...geo,lat: txt||undefined}) } />
                 </InputLine>
                 <InputLine label={`经度(点选地图坐标):`}>
                     <CommitInput  value={ geo.lon || ''}  onSave={txt => setGeo({...geo,lon: txt||undefined}) } />
                 </InputLine>

                 <Button
                     intent="primary"
                     css={{ marginLeft: theme.spaces.sm }}
                     onPress={() => {
/*                         createfunc({town,county,city,province,country, name:adrname, lat:geo.lat, lon:geo.lon,
                             vlg: vlg?.id, plcls, seimp, dense
                         });*/
                     }}
                 >登记新地址
                 </Button>
             </Collapse>
         </Layer>

         <Dialog   mobileFullscreen  isOpen={open}
            onRequestClose={() => setOpen(false)}
            title="从已确认地址当中挑选"
            css={{        //上级窗口已经限制高度，要在里面滚动适应。
               overflow: 'auto',    //替换掉Dialog底层组件默认visible：默认是任意生长高度；我这要限制高度里面嵌套组件可滚动列表的；只能二选一方式。
               [theme.mediaQueries.md]: {
               },
               [theme.mediaQueries.xl]: {
               }
            }}
        >
           <div
               css={{        //上级窗口已经限制高度，要在里面滚动适应。
                   //去掉抬头标题的高度
                   height: `calc(100vh - ${theme.spaces.lg} - 40px)`,
                   [theme.mediaQueries.md]: {
                       height: `calc(100vh - ${theme.spaces.lg} - 40px - 2 * 30px - 1rem)`
                   },
                   [theme.mediaQueries.xl]: {
                       height: `calc(100vh - ${theme.spaces.lg} - 40px - 2 * 30px - 1rem)`
                   }
               }}
           >
               <ErrorBoundary fallbackRender={({ error }) => <div>{error.message}</div>}>
{/*                   <React.Suspense fallback="等下马上来...">
                       { posQreference && <PositionListInner queryReference={posQreference} onSelect={handleSelect} /> }
                   </React.Suspense>*/}
               </ErrorBoundary>
           </div>
        </Dialog>

     </React.Fragment>
    );
}

